package com.imon.jmxbox;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

@Component
public class BackOfficeImpl implements BackOffice {

	private static final Log LOG = LogFactory.getLog(BackOfficeImpl.class);

	@Resource
	private ConnectionFactory connectionFactory;

	@Resource
	private Destination destination;

	public Mail receiveMail() {

		Connection conn = null;

		try {
			conn = connectionFactory.createConnection();
			Session session = conn.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			MessageConsumer consumer = session.createConsumer(destination);
			conn.start();

			MapMessage message = (MapMessage) consumer.receive();

			Mail mail = new Mail(message.getString("mailId"),
					message.getString("country"), message.getDouble("weight"));
			session.close();

			return mail;

		} catch (JMSException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (JMSException e) {
					LOG.error("Unable to close connection", e);
				}
			}
		}
	}
}
